<?php

namespace App\Exports;

use App\Models\NetCourseCdkey;
use Carbon\Carbon;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithStyles;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Border;
use PhpOffice\PhpSpreadsheet\Style\Fill;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;

class QhNetCourseCdkeyExport implements FromCollection, WithStyles
{
    protected array $params;
    public function __construct($params)
    {
        $this->params = $params;
    }

    public function styles(Worksheet $sheet)
    {
        $highestRow = $sheet->getHighestRow();
        $highestColumn = $sheet->getHighestColumn();
        $highestColumnIndex = Coordinate::columnIndexFromString($highestColumn);

        // 设置整个表格的列宽
        for ($i = 1; $i <= $highestColumnIndex; $i++) {
            $sheet->getColumnDimension(Coordinate::stringFromColumnIndex($i))->setWidth(30);
        }

        // 设置整个表格的垂直居中和水平居中
        $sheet->getStyle('A1:'.$highestColumn.$highestRow)->getAlignment()->setVertical(Alignment::VERTICAL_CENTER);
        $sheet->getStyle('A1:'.$highestColumn.$highestRow)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);

        // 设置整个表格的字体大小
        $sheet->getStyle('A1:'.$highestColumn.$highestRow)->getFont()->setSize(12)->setName('宋体');

        // 设置整个表格的行高
        $sheet->getDefaultRowDimension()->setRowHeight(22);

        // 添加边框样式到所有单元格
        $sheet->getStyle('A1:'.$highestColumn.$highestRow)->getBorders()->getAllBorders()->setBorderStyle(Border::BORDER_THIN);

        return [];
    }

    /**
    * @return Collection
    */
    public function collection(): Collection
    {
        return new Collection($this->createData());
    }

    public function createData(): array
    {
        $cdkeyList = NetCourseCdkey::whereIn('id', $this->params['ids'])->get();

        $collect = [
            ['激活码', '状态', '生成时间', '激活码过期时间', '激活时间', '使用者', '渠道', '资源有效期']
        ];

        $cdkeyStatus = [
            1 => '未使用',
            2 => '已使用',
            3 => '已失效',
            4 => '已冻结',
        ];

        foreach ($cdkeyList as $cdkey) {
            $collect[] = [
                $cdkey->code,
                !empty($cdkeyStatus[$cdkey->status]) ? $cdkeyStatus[$cdkey->status] : '无效状态',
                $cdkey->created_at ? Carbon::make($cdkey->created_at)->format('Y-m-d H:i:s') : '-',
                $cdkey->expires ? Carbon::make($cdkey->expires)->format('Y-m-d H:i:s') : '-',
                $cdkey->useAt ? Carbon::make($cdkey->useAt)->format('Y-m-d H:i:s') : '-',
                $cdkey->user ? '[ID:'.$cdkey->user->id.']'.$cdkey->user->nickname : '-',
                $cdkey->group ? $cdkey->group->channel : '',
                $cdkey->effectiveAt ? $cdkey->effectiveAt : '',
            ];
        }

        return $collect;
    }


}
